package com.ibeetl.admin.core.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import com.ibeetl.admin.core.entity.CoreArea;
import com.ibeetl.admin.core.rbac.tree.AreaItem;

public class AreaBuildUtil {
    private AreaBuildUtil() {

    }

    public static AreaItem buildAreaTree(Long rootAreaCode, List<CoreArea> list) {
        CoreArea root = new CoreArea();
        root.setId(0L);
        root.setName("地区");
        root.setAreaCode(rootAreaCode != null ? rootAreaCode : 0L);
        AreaItem rootArea = new AreaItem(root);
        buildTreeNode(rootArea, list);
        return rootArea;
    }
    public static AreaItem buildAreaTableTree(List<CoreArea> list) {
    	CoreArea root = new CoreArea();
    	root.setId(0L);
    	root.setName("主菜单");
    	AreaItem rootArea = new AreaItem(root);
    	buildTreeNode(rootArea, list);
    	return rootArea;
    }

    private static void buildTreeNode(AreaItem parent, List<CoreArea> list) {

        long code = parent.getAreaCode();
        List<CoreArea> dels = new ArrayList<>();
        for (CoreArea sysArea : list) {
            if (sysArea.getParentCode() == code) {
                AreaItem item = new AreaItem(sysArea);
                item.setParent(parent);
                dels.add(sysArea);
            }
        }
        list.removeAll(dels);

        if (list.isEmpty()) {
            return;
        }
        
        sortArea(parent.getChildren());
        
        for (AreaItem child : parent.getChildren()) {
            buildTreeNode(child, list);
        }
    }
    
	private static void sortArea(List<AreaItem> children) {
		Collections.sort(children, new Comparator<AreaItem>() {

			@Override
			public int compare(AreaItem o1, AreaItem o2) {
				return o1.getSeq().compareTo(o2.getSeq());
			}
			
		});
		
	}

}
